package com.loren.demo03.tcp2.handler;

import com.loren.demo03.tcp2.protocol.MsgProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class DecoderHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        if (in.readableBytes() > MsgProtocol.DATA_MIN_LENGTH) {
            in.markReaderIndex();
            byte head = in.readByte();
            if (head == MsgProtocol.DATA_HEAD) {
                int dataLength = in.readInt();
                if (dataLength >= in.readableBytes()) {
                    in.resetReaderIndex();
                    return;
                }
                byte[] content = new byte[dataLength];
                in.readBytes(content);
                byte tail = in.readByte();
                if (tail == MsgProtocol.DATA_TAIL) {
                    out.add(content);
                }
            }
        }
    }
}
